package com.controller.briuptest;

import com.pojo.User;
import com.service.UserService;
import com.utils.Result;
import com.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
//用户
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result findUserById(@PathVariable Integer id) throws Exception {
        User user = userService.findUserById(id);
        System.out.println(user.toString());
        return Result.SUCCESS(user, ResultCode.SEARCH_SUCCESS);
    }
    @RequestMapping(value = "",method = RequestMethod.POST,consumes = "application/json")
    @ResponseBody
    public Result addUser(@RequestBody User user) throws Exception{
        if(userService.addUser(user)){
            return Result.SUCCESS(user,ResultCode.ADD_SUCCESS);
        }else return Result.failure(ResultCode.DATA_WRONG);
    }
    @RequestMapping(value = "",method = RequestMethod.PUT)
    @ResponseBody
    public Result updateUser(@RequestBody User user) throws Exception{
        System.out.println(user.toString());
        if(userService.updateUser(user)){
            return  Result.SUCCESS(user,ResultCode.UPDATE_SUCCESS);
        }else return Result.failure(ResultCode.DATA_WRONG);
    }
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public Result deleteUser(@PathVariable Integer id) throws Exception{
        System.out.println(id);
        if(userService.deleteUser(id)){
            return Result.SUCCESS(null,ResultCode.DELETE_SUCCESS);
        }else return Result.failure(ResultCode.DATA_WRONG);
    }
    @RequestMapping(value = "/all",method = RequestMethod.GET)
    @ResponseBody
    public Result findAllUser() throws Exception{
        List<User> userList=userService.findAllUser();
        if(userList!=null){
            return Result.SUCCESS(userList,ResultCode.SEARCH_SUCCESS);
        }else return Result.failure(ResultCode.DATA_WRONG);
    }
}
